<?php

	namespace org\tekuna\framework\request;

	use org\tekuna\base\Tekuna;
	
	use org\tekuna\framework\filter\Filter;

	
	/**
	 * This class provides request parameter information for Cli requests. All
	 * parameters are filtered before delivery.
	 */
	class CliRequest extends Request {

		private
			$arrRawArgs = array(),
			$arrArgFilters = array();

		protected function init() {

			global $argv;
			
			// initialize the logger
			$this -> objLogger = Tekuna :: getLogger(__CLASS__);

			// import the raw values
			$this -> arrRawArgs = $_SERVER['argv'];

			// clear raw values
			$argv = array();
			$_SERVER['argv'] = array();
		}

		/**
		 * Set a filter object for a certain argument.
		 *
		 * @param integer $iArgNo the argument number
		 * @param Filter a filter object
		 */
		public function setArgumentFilter($iArgNo, Filter $objFilter) {

			$this -> arrArgFilters[$iArgNo] = $objFilter;
		}


		/**
		 * Returns the filter for a specific script argument. If
		 * no special filter is set (and implicitly the default filter
		 * would be applied) this method returns NULL.
		 *
		 * @param integer $iArgNo the argument number
		 * @return Filter object or NULL
		 */
		public function getArgumentFilter($iArgNo) {

			if (isset($this -> arrArgFilters[$iArgNo])) {

				return $this -> arrArgFilters[$iArgNo];
			}
			else {

				return NULL;
			}
		}


		/**
		 * Returns a value from the script arguments. If the value is not available
		 * a RequestException is thrown. The defined filter (or the default filter)
		 * is applied to the value and (if it is an array) all values in any depth.
		 *
		 * @param integer $iArgNo the argument number
		 * @return string the value of this argument
		 */
		public function getArgument($iArgNo) {

			if (! isset($this -> arrRawArgs[$iArgNo])) {

				throw new RequestException("The argument #$iArgNo is not available.");
			}

			$objFilter = NULL;
			if (isset($this -> arrArgFilters[$iArgNo])) {

				$objFilter = $this -> arrArgFilters[$iArgNo];
			}
			else {

				$objFilter = $this -> objDefaultFilter;
			}

			return $this -> applyFilterRecursive($this -> arrRawArgs[$iArgNo], $objFilter);
		}


		/**
		 * @return array returns an array of all arguments.
		 */
		public function getAllArguments() {

			$arrReturn = array();

			foreach (array_keys($this -> arrRawArgs) as $iArgNo) {

				$arrReturn[$iArgNo] = $this -> getArgument($iArgNo);
			}

			return $arrReturn;
		}
		
		
		/**
		 * @return integer returns the count of arguments
		 */
		public function getArgumentCount() {
			
			return count($this -> arrRawArgs);
		}
	}


